package com.yc.demo.d0304;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 设置字符集编码
 */
@WebFilter(filterName = "EncodingFilter",value = "*.s")
public class EncodingFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
        //初始化方法
        System.out.println("EncodingFilter 初始化");
    }

    public void destroy() {
        //销毁
        System.out.println("EncodingFilter 销毁");
    }

    //chain 过滤器链
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        System.out.println("EncodingFilter 执行过滤(前)");

        request.setCharacterEncoding("utf-8");

        response.setCharacterEncoding("utf-8");
        response.setContentType("apllication/json;charset=utf-8");
        //执行后续过滤器，如无则送达目标资源
        chain.doFilter(request, response);
        //请求到打目标自愿后响应过程会执行过滤器链后的代码
        System.out.println("EncodingFilter 执行过滤(后)");
    }
}
